package com.geovis.boot.service.demo.file.security;


import com.alibaba.fastjson.JSONObject;
import com.geovis.boot.common.util.RedisUtils;
import com.geovis.boot.service.demo.file.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    RedisUtils redisUtil;



    @Resource
    UserService userService;

    @Resource
    RedisAuthenticationFilter redisAuthenticationFilter;


    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {


        //生成token
        String userName = ((User) authentication.getPrincipal()).getUsername();
        String token = BCrypt.hashpw(userName, BCrypt.gensalt());

        //将token存入redis
        redisUtil.set(token, userName, 8 * 3600);
//        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

//        String token = Jwts.builder()
//                .setSubject(((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername())
//                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
//                .signWith(SignatureAlgorithm.HS512, "MyKey")
//                .compact();

        //将token返回
        // System.out.println(token);
        response.setContentType("application/json;charset=UTF-8");
        response.addHeader("Authorization", "Bearer " + token);
        //response.getWriter().print("name: "+ username +" token: "+ token );


        //用户id
        Integer user_id = userService.queryByUserName(userName).getId();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("id", user_id);
        jsonObject.put("teoken", token);
        String jsonStr = JSONObject.toJSONString(jsonObject);

        PrintWriter print = response.getWriter();
        print.print(jsonStr);
        print.flush();
        print.close();

    }


}